from decimal import Decimal
from django.db import transaction
from django.shortcuts import get_object_or_404
from orders.models import Order, OrderItem, MenuItem, Restaurant
from orders.utils.validators import validate_order_items, validate_quantity

class OrderService:
    @staticmethod
    @transaction.atomic
    def create_order(user, restaurant_id, items_data, delivery_address):
        """Create a new order with the given items."""
        # Validate order items
        validate_order_items(items_data)
        
        restaurant = get_object_or_404(Restaurant, pk=restaurant_id)
        order = Order.objects.create(
            customer=user,
            restaurant=restaurant,
            total_amount=Decimal('0'),
            delivery_address=delivery_address
        )
        
        total = Decimal('0')
        order_items = []
        
        # Process order items
        for item_id, quantity in items_data.items():
            if item_id.startswith('item_') and quantity:
                try:
                    quantity = int(quantity)
                    validate_quantity(quantity)
                    
                    menu_item = get_object_or_404(
                        MenuItem,
                        pk=int(item_id.split('_')[1]),
                        is_available=True
                    )
                    
                    order_item = OrderItem(
                        order=order,
                        menu_item=menu_item,
                        quantity=quantity,
                        price=menu_item.price
                    )
                    order_items.append(order_item)
                    total += menu_item.price * quantity
                    
                except (ValueError, TypeError):
                    continue
        
        # Bulk create order items
        OrderItem.objects.bulk_create(order_items)
        
        order.total_amount = total
        order.save()
        return order

    @staticmethod
    def get_user_orders(user):
        """Get all orders for a user."""
        return Order.objects.filter(
            customer=user
        ).select_related(
            'restaurant'
        ).order_by('-created_at')

    @staticmethod
    def get_order_detail(order_id, user):
        """Get detailed order information."""
        return get_object_or_404(
            Order.objects.select_related('restaurant').prefetch_related(
                'orderitem_set__menu_item'
            ),
            pk=order_id,
            customer=user
        )